<?php

namespace app\model;

//use support\Model;
use app\controller\wmapi\IndexController;
use support\Db;
use Illuminate\Database\Eloquent\Model;
use function GuzzleHttp\json_decode;

class WaAccountingInformationRelevance
{
//accountinginformation
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'wa_order_account_information_relevance';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;


    /**
     * 出账单列表
     * @param $page
     * @param $pageNum
     * @param string[] $fields
     * @param array $condition
     */
    public static function list($page, $pageNum, $fields = ['*'], $condition = [], $between = [])
    {
        $condition [] = ['is_show', '=', 1];
        $offset = ($page - 1) * $pageNum;
        if ($between) {
            $model = Db::table('wa_order_account_information_relevance')
                ->select($fields)
                ->where($condition)
                ->whereBetween('created_at', $between);
        } else {
            $model = Db::table('wa_order_account_information_relevance')
                ->select($fields)
                ->where($condition);
        }


        $count = $model->count();
        $list = $model
            ->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($pageNum)
            ->get();

        if ($list) {
            foreach ($list as $k) {
                if ($k->payment_voucher) {
                    $k->payment_voucher = json_decode($k->payment_voucher);
                }
                if ($k->voucher) {
                    $k->voucher = json_decode($k->voucher);
                }

                if ($k->status == 1) {
                    $k->status_name = '待确认到账';
                } elseif ($k->status == 2) {
                    $k->status_name = '已到账';
                } elseif ($k->status == 3) {
                    $k->status_name = '异常';
                } else {
                    $k->status_name = '';
                }

                if ($k->type == 1) {
                    $k->type_name = '定金';
                } elseif ($k->type == 2) {
                    $k->type_name = '余款';
                } else {
                    $k->type_name = '';
                }

                // 货币类型   1 人民币 2 美元 3 欧元
//                if ($k->currency == 1){
//                    $k->currency_name = '人民币';
//                }elseif ($k->currency == 2){
//                    $k->currency_name = '美元';
//                }elseif ($k->currency == 3){
//                    $k->currency_name = '欧元';
//                }else{
//                    $k->currency_name = '';
//                }
                $k->currency_name = IndexController::currencyNameCommon($k->currency);


            }
        }

        return json_encode(['list' => $list, 'count' => $count]);


    }


    /**
     * @param $page
     * @param $pageNum
     * @param string[] $fields
     * @param array $condition
     */
    public static function all($fields, $condition)
    {

        $list = Db::table('wa_order_account_information_relevance')
            ->select($fields)
            ->where($condition)
            ->get();

        if ($list) {
            foreach ($list as $k) {
//                if ($k->payment_voucher) {
//                    $k->payment_voucher = json_decode($k->payment_voucher);
//                }
//                if ($k->voucher) {
//                    $k->voucher = json_decode($k->voucher);
//                }
                //'(订单)状态 0 待审批 1正常(通过) 2审批失败 3 作废 4 删除',
                if ($k->status == 0) {
                    $k->status_name = '待审批';
                } elseif ($k->status == 1) {
                    $k->status_name = '正常(通过/已分配)';
                } elseif ($k->status == 2) {
                    $k->status_name = '2审批失败';
                } elseif ($k->status == 3) {
                    $k->status_name = '作废';
                } elseif ($k->status == 4) {
                    $k->status_name = '删除';
                } else {
                    $k->status_name = '';
                }
                $k->deposit_acc_status = 1;
                $k->deposit_acc_status_name = '定金未到账';
                $k->balance_acc_status = 1;
                $k->balance_acc_status_name = '尾款未到账';
                // 入账类型 1 定金  2 余款
                if ($k->type == 1) {
                    $k->type_name = '定金';
                    // 定金的状态 定金未到账  定金未足额到账 定金足额到账
                    $sales_fund_deposit_type_condition = [];
                    $sales_fund_deposit_type_condition [] = ['order_sn_parent','=',$k->order_sn_parent]; //
                    $sales_fund_deposit_type_condition [] = ['type','=',1]; // 定金
                    $sales_fund_deposit_type_where_in = [0,1]; // 待审批和通过审批
                    $deposit_acc_price = WaAccountingInformationRelevance::sumsBySaesFundType($sales_fund_deposit_type_condition, $sales_fund_deposit_type_where_in);

                    $sales_deposit_condition = [];
                    $sales_deposit_condition [] = ['order_sn','=',$k->order_sn_parent]; //
                    $sales_data = WaOrders::find($sales_deposit_condition);
                    $sales_data = json_decode($sales_data);
                    if ($sales_data){
                        $deeposit_amount = $sales_data->deeposit_amount;
                    }else{
                        $deeposit_amount = 0;
                    }


                    if (!$deposit_acc_price){
                        $k->deposit_acc_status = 1;
                        $k->deposit_acc_status_name = '未到账';
                    }elseif(round($deposit_acc_price,2)>0){
                        if (round($deposit_acc_price,2) == round($deeposit_amount,2)){
                            $k->deposit_acc_status = 2;
                            $k->deposit_acc_status_name = '足额到账';
                        }else{
                            $k->deposit_acc_status = 3;
                            $k->deposit_acc_status_name = '未足额到账';
                        }
                    }

                } elseif ($k->type == 2) {
                    $k->type_name = '余款';
                    // 尾款的状态 尾款未到账  尾款未足额到账 尾款足额到账
                    $sales_fund_balance_type_condition = [];
                    $sales_fund_balance_type_condition [] = ['order_sn_parent','=',$k->order_sn_parent]; //
                    $sales_fund_balance_type_condition [] = ['type','=',2]; // 尾款
                    $sales_fund_balance_type_where_in = [0,1]; // 待审批和通过审批
                    $balance_acc_price= WaAccountingInformationRelevance::sumsBySaesFundType($sales_fund_balance_type_condition, $sales_fund_balance_type_where_in);

                    $sales_balance_condition = [];
                    $sales_balance_condition [] = ['order_sn','=',$k->order_sn_parent]; //
                    $sales_data = WaOrders::find($sales_balance_condition);
                    $sales_data = json_decode($sales_data);
                    if ($sales_data){
                        if ($sales_data->deeposit_amount){
                            $balance_amount = round($sales_data->total_amount,2) - round($sales_data->deeposit_amount,2);
                        }else{
                            $balance_amount = round($sales_data->total_amount,2);
                        }
                    }else{
                        $balance_amount = 0;
                    }

                    if (!$balance_acc_price){
                        $k->balance_acc_status = 1;
                        $k->balance_acc_status_name = '未到账';
                    }elseif(round($balance_acc_price,2)>0){
                        if (round($balance_acc_price,2) == $balance_amount){
                            $k->balance_acc_status = 2;
                            $k->balance_acc_status_name = '足额到账';
                        }else{
                            $k->balance_acc_status = 3;
                            $k->balance_acc_status_name = '未足额到账';
                        }
                    }
                } else {
                    $k->type_name = '';
                }


                // 货币类型   1 人民币 2 美元 3 欧元
//                if ($k->currency == 1){
//                    $k->currency_name = '人民币';
//                }elseif ($k->currency == 2){
//                    $k->currency_name = '美元';
//                }elseif ($k->currency == 3){
//                    $k->currency_name = '欧元';
//                }else{
//                    $k->currency_name = '';
//                }
                $k->currency_name = IndexController::currencyNameCommon($k->currency);
                $sum_data = WaAccountingInformationRelevance::billDetailsByOrderSn($k->order_sn_parent);
                if ($sum_data) {
                    $sum_data = json_decode($sum_data);
                }
                $k->sum_data = $sum_data;

                // 获取账单信息(销售订单详情列表要展示)
                if ($k->finance_no) {
                    $acc_info_condition = [];
                    $acc_info_condition [] = ['finance_no', '=', $k->finance_no];
                    $acc_info = WaAccountingInformation::find($acc_info_condition);
                    $acc_info = json_decode($acc_info);
                    if($acc_info){
                        $k->payer_name = $acc_info->payer_name;
                        $k->receipt_number = $acc_info->receipt_number;
                        $k->payment_voucher = $acc_info->payment_voucher;
                    }
                } else {
                    $acc_info = [];
                    $k->payer_name = '';
                    $k->receipt_number = '';
                    $k->payment_voucher = '';
                }

                $k->acc_info = $acc_info;

            }
        }
        return json_encode($list);


    }


    /**
     * 某笔账单的详情及其明细
     * @param $condition
     * @return false|string
     */
    public static function find($condition)
    {
        $res = Db::table('wa_order_account_information_relevance')
            ->select('*')
            ->where($condition)
            ->first();
        if ($res) {
            $k = $res;
//            if ($k->payment_voucher){
//                $k->payment_voucher = json_decode($k->payment_voucher);
//            }
//            if ($k->voucher){
//                $k->voucher = json_decode($k->voucher);
//            }

            if ($k->status == 1) {
                $k->status_name = '待确认到账';
            } elseif ($k->status == 2) {
                $k->status_name = '已到账';
            } elseif ($k->status == 3) {
                $k->status_name = '异常';
            } else {
                $k->status_name = '';
            }

            if ($k->type) {
                $k = IndexController::accountingInformationTypeName($k);
            }
            // 获取订单关联信息
//            $order_relevance = [];
//            if ($k->order_sn_parent){
//                foreach ($k->order_sn_parent as $kp){
//                    $osp = WaAccountingInformationRelevance::billDetailsByOrderSn($kp);
//                    array_push($order_relevance,$osp);
//                }
//            }

//            $k->order_relevance = $order_relevance;

            // 货币类型   1 人民币 2 美元 3 欧元
//            if ($k->currency == 1){
//                $k->currency_name = '人民币';
//            }elseif ($k->currency == 2){
//                $k->currency_name = '美元';
//            }elseif ($k->currency == 3){
//                $k->currency_name = '欧元';
//            }else{
//                $k->currency_name = '';
//            }

            $k->currency_name = IndexController::currencyNameCommon($k->currency);

            $res = $k;
        }
        return json_encode($res);
    }

    public static function created($data)
    {
        return Db::table('wa_order_account_information_relevance')->insertGetId($data);
    }

    public static function updated($data, $where)
    {
        $result = Db::table('wa_order_account_information_relevance')->where($where)->update($data);
        return $result;
    }

    /**
     * 某笔订单的交易账单明细
     */
    public static function billDetailsByOrderSn($orderSn)
    {

        $sales_condition = [];
        $sales_condition [] = ['order_sn', '=', $orderSn];
        $sales_data = WaOrders::find($sales_condition);
        if ($sales_data) {
            $sales_data = json_decode($sales_data);
        }


//        $sales_relevance_condition = [];
//        $sales_relevance_condition [] = ['order_sn_parent', '=', $orderSn];
//        $sales_relevance_field = ['*'];
////        $sales_relevance_data = WaAccountingInformationRelevance::find($sales_relevance_condition);
//        $sales_relevance_data = WaAccountingInformationRelevance::all($sales_relevance_field,$sales_relevance_condition);
//        if ($sales_relevance_data) {
//            $sales_relevance_data = json_decode($sales_relevance_data);
//        }else{
//            $sales_relevance_data = '';
//        }


        // 出/入账类型 1定金  2 余款 3 定金退款 4 尾款退款 5 客户违约金 6 赔付金
        // 账单状态 1待财务确认到账(默认) 2待分配  3 到账异常' 4作废
        //  分配状态 0 待审批 1正常(通过) 2审批失败 3 作废 4删除',
        // 账单总分配定金
        $deposit_price_all = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 1]],
            []
        );

        // 已分配到销售订单定金(审批通过)
        $deposit_assigned = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 1]],
            [1]
        );

        // 已提交分配申请销售订单定金(待审核)
        $deposit_applied = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 1]],
            [0]
        );

        // 待分配定金
        $deposit_to_be_allocated = round($sales_data->deeposit_amount, 2) - round($deposit_price_all, 2);


        // 账单总分配尾款
        $balance_payment_all = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 2]],
            []
        );


        // 已分配到销售订单尾款(审批通过)
        $balance_assigned = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 2]],
            [1]
        );
        // 已提交分配申请销售订单尾款(待审核)
        $balance_applied = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 2]],
            [0]
        );
        //尾款 订单总尾款
        $balance_all = round($sales_data->total_amount, 2) - round($sales_data->deeposit_amount, 2); // 销售订单总尾款
        // 待分配尾款
        $balance_to_be_allocated = round($balance_all, 2) - round($balance_payment_all, 2);


        // 定金退款总额
        $deposit_return_all = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 3]],
            []
        );
        // 尾款退款总额
        $balance_payment_return_all = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 4]],
            []
        );
        // 客户违约金
        $liquidated_damages_all = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 5]],
            []
        );
        // 赔付金
        $compensation_money_all = WaAccountingInformationRelevance::sumsBySaesFundType(
            [['order_sn_parent', '=', $orderSn], ['type', '=', 6]],
            []
        );

        $res = [

            'deeposit_amount' => round($sales_data->deeposit_amount, 2), // 定金 订单总定金(应收金额)

            'deposit_price_all' => $deposit_price_all, // 账单总分配定金（审批通过 + 待审核）
            'deposit_assigned' => $deposit_assigned, // 已分配到销售订单定金(审批通过)
            'deposit_applied' => $deposit_applied, // 已已提交分配申请销售订单定金(待审核)
            'deposit_to_be_allocated' => $deposit_to_be_allocated, // 待分配定金

            'balance_all' => $balance_all, // 尾款 订单总尾款(应收金额)
            'balance_payment_all' => $balance_payment_all, // 账单总分配尾款（审批通过 + 待审核）
            'balance_assigned' => $balance_assigned, // 已分配到销售订单尾款(审批通过)
            'balance_applied' => $balance_applied, // 已提交分配申请销售订单尾款(待审核)
            'balance_to_be_allocated' => $balance_to_be_allocated, // 待分配尾款

            'deposit_return_all' => $deposit_return_all, // 定金退款
            'balance_payment_return_all' => $balance_payment_return_all, // 尾款退款
            'liquidated_damages_all' => $liquidated_damages_all, // 违约金
            'compensation_money_all' => $compensation_money_all, // 补偿金


//            'sales_relevance_data' => $sales_relevance_data, // 账单分配详情


        ];

        return json_encode($res);
    }

    /**
     * 统计某笔账单(订单)的金额 - 根据type类型
     * @param $sales_fund_type_condition
     * @param $sales_fund_type_where_in
     * @return float|mixed
     */
    public static function sumsBySaesFundType($sales_fund_type_condition, $sales_fund_type_where_in)
    {
        if ($sales_fund_type_where_in) {
            $sales_fund_type_where_in = $sales_fund_type_where_in;
        } else {
            $sales_fund_type_where_in = [0, 1];
        }
        $result = Db::table('wa_order_account_information_relevance')->where($sales_fund_type_condition)->whereIn('status', $sales_fund_type_where_in)->sum('transfer_amount');
        if ($result) {
            $result = round($result, 2);
        } else {
            $result = 0.00;

        }
        return $result;
    }

    /**
     *  统计某笔账单的金额 - 根据 finance_no
     * @param $sales_fund_type_condition
     * @param $sales_fund_type_where_in
     * @return float|mixed
     */
    public static function sumsBySalesFundByFinanceNo($sales_fund_type_condition, $sales_fund_type_where_in)
    {
        if ($sales_fund_type_where_in) {
            $sales_fund_type_where_in = $sales_fund_type_where_in;
        } else {
            $sales_fund_type_where_in = [0, 1];
        }
        $result = Db::table('wa_order_account_information_relevance')->where($sales_fund_type_condition)->whereIn('status', $sales_fund_type_where_in)->sum('transfer_amount');
        if ($result) {
            $result = round($result, 2);
        } else {
            $result = 0.00;

        }
        return $result;
    }


}